package com.bprogram.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bprogram.Enum.UserRole;
import com.bprogram.dto.Mail;
import com.bprogram.dto.MailBox;
import com.bprogram.mapper.UserMapper;
import com.bprogram.pojo.User;
import com.bprogram.service.UserService;
import com.bprogram.utils.IdGenerator;
import com.bprogram.utils.RedisUtil;
import com.bprogram.utils.SendMailUtil;
import com.bprogram.utils.ValidateCodeUtils;


import com.sun.mail.smtp.SMTPSendFailedException;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;


import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cai
 * @since 2023-11-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisUtil redisUtil;
    @Autowired
    private MailBox mailBox;

    @Override
    public boolean register(User user) {
        long userId = new IdGenerator().snowflakeId();
        //随机生成账号，redis校验是否存在这个账号，是继续生成否放入
        String code = ValidateCodeUtils.generateValidateCode4String(11);
        boolean isExist = true;
        while (isExist) {
            if (redisUtil.sSet("userCode", code) == 0) {
                code = ValidateCodeUtils.generateValidateCode4String(11);
            } else {
                isExist = false;
            }
        }
        System.out.println(code);
//将明文密码存到redis
        redisUtil.hset("userPwd", user.getUserEmail(), user.getUserPwd());
        /**
         * algorithmName:加密方式
         * source：需要加密的数据
         * salt：数据类型byte[]，盐值，可以选择自定义或者使用默认值。盐值是一个随机数，用于增强密码的安全性。如果不指定盐值，则使用默认值。
         * hashIterations：加密次数
         */
//        SecureRandom random = new SecureRandom();
//        byte[] salt = new byte[16];
//        random.nextBytes(salt);
        SimpleHash simpleHash = new SimpleHash("MD5", user.getUserPwd(), null, 2);
        String userPassword = simpleHash.toString();
        user.setUserId(userId)
                .setUserPwd(userPassword)
                .setCreateId(userId)
                .setUserCode(code)
                //设置默认头像
                .setUserAvatarId(666l)
                .setUserAvatar("https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png")
                .setPerms(UserRole.NORMAL.getKey())
                .setUserSign("如果我是IKUN，你会爱我吗！")
                .setCreateCode(code)
                .setCreateName(user.getUserName())
                .setCreateTime(null);
        boolean isSuccess = this.save(user);
        Mail mail = new Mail();
        mail.setSubject("bprogram");
        mail.setText("<h1>注册成功！</h1> <br />您的账号是是：" + code + "赶快去登录吧");
        if (isSuccess) {
            sendEmail(mailBox, mail, user.getUserEmail());
        }
        return isSuccess;

    }

    @Override
    public int getCodeNum(String userEmail) {
        return userMapper.getCodeNum(userEmail);
    }

    /**
     * 发送邮箱
     *
     * @param mailBox
     * @param mail
     * @param to      发送对象
     * @return
     */
    public void sendEmail(MailBox mailBox, Mail mail, String to) {
        SendMailUtil sendMail = SendMailUtil.getSingleton();
        mail.setSendTo(to);
        sendMail.setProperties(mailBox);
        sendMail.setMail(mail);
        try {
            sendMail.sendQQSmtpEmail();
        } catch (SMTPSendFailedException e) {
            Assert.isTrue(false, "请输入有效的邮箱！");
        } catch (Exception e) {
            e.printStackTrace();
            Assert.isTrue(false, "邮箱格式错误，获取验证码失败，请重新获取");
        }
    }

    /**
     * @param currentPage 当前页
     * @param pageSize    一页有多少条数据
     * @param userCode    查询条件
     * @return
     */
    @Override
    public IPage<User> pageList(String currentPage, String pageSize, String userCode) {
        IPage<User> page = new Page<>();
        long ps = Long.parseLong(pageSize);
        long cp = Long.parseLong(currentPage);
        page.setSize(ps);
        page.setCurrent(cp);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(userCode)) {
            wrapper.eq("userCode", userCode);
        }
        IPage<User> userPage = userMapper.selectPage(page, wrapper);
        List<User> userList = userPage.getRecords();
        return userPage;
    }

    @Override
    public boolean userDelete(long id) {
        int result = userMapper.deleteById(id);
        if (result > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean updateUser(User user) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        User user1 = new User();
        if (!StringUtils.isEmpty(user.getPerms())) {
            user1.setPerms(user.getPerms());
        }
        if (!StringUtils.isEmpty(user.getUserName())) {
            user1.setUserName(user.getUserName());
        }
        if (!StringUtils.isEmpty(user.getIsBlack())) {
            user1.setIsBlack(user.getIsBlack());
        }
        if (!StringUtils.isEmpty(user.getUserAvatar())) {
            user1.setUserAvatarId(666l);
            user1.setUserAvatar(user.getUserAvatar());
        }
        if (!StringUtils.isEmpty(user.getIsVIP())) {
            user1.setIsVIP(user.getIsVIP());
        }

        //修改个人信息
        if (!StringUtils.isEmpty(user.getUserBirthday())) {
            user1.setUserBirthday(user.getUserBirthday());
        }
        updateWrapper.eq("userId", user.getUserId());
        return this.update(user1, updateWrapper);
    }


}
